package com.hanyxx.thread.lock;

import lombok.SneakyThrows;

/**
 * @author layman
 * @date 2021/2/9
 */
public class Demo08 {
    public static void main(String[] args) throws InterruptedException {
        Demo08Service service = new Demo08Service();
        Demo08ThreadA t1 = new Demo08ThreadA(service);
        Demo08ThreadA t2 = new Demo08ThreadA(service);
        //t1的线程状态：NEW
        System.out.println("t1的线程状态：" + t1.getState());
        t1.start();
        //t1的线程状态：RUNNABLE
        System.out.println("t1的线程状态：" + t1.getState());
        //确保t1线程先启动
        Thread.sleep(500L);
        //t1的线程状态：TIMED_WAITING
        System.out.println("t1的线程状态：" + t1.getState());
        t2.start();
        //t2的线程状态：RUNNABLE? 为什么不是BLOCKED?奇怪?
        System.out.println("t2的线程状态：" + t2.getState());
        Thread.sleep(5000L);
        //t1的线程状态：TERMINATED
        System.out.println("t1的线程状态：" + t1.getState());

        Demo08ThreadB t3 = new Demo08ThreadB(new Object());
        t3.start();
        Thread.sleep(100L);
        //t3的线程状态：WAITING
        System.out.println("t3的线程状态：" + t3.getState());
    }
}
class Demo08Service{
    public synchronized void doSomething() throws InterruptedException {
        Thread.sleep(3000L);
    }
}
class Demo08ThreadA extends Thread{
    private Demo08Service service;
    public Demo08ThreadA(Demo08Service service){
        this.service = service;
    }
    @SneakyThrows
    @Override
    public void run() {
        service.doSomething();
    }
}
class Demo08ThreadB extends Thread{
    private Object lock;
    public Demo08ThreadB(Object lock){
        this.lock = lock;
    }
    @SneakyThrows
    @Override
    public void run() {
        synchronized (lock){
            lock.wait();
        }
    }
}
